<?php

namespace Kangcg\WeChat;

use Kangcg\Application\Base\Event;
use Kangcg\WeChat\Library\Urls;
use Kangcg\WeChat\Library\WeChat\Comment;
use Kangcg\WeChat\Library\WeChat\Draft;
use Kangcg\WeChat\Library\WeChat\Media;
use Kangcg\WeChat\Library\WeChat\Menu;
use Kangcg\WeChat\Library\WeChat\MessageFK;
use Kangcg\WeChat\Library\WeChat\MessageMass;
use Kangcg\WeChat\Library\WeChat\MessageServer;
use Kangcg\WeChat\Library\WeChat\MessageTemplate;
use Kangcg\WeChat\Library\WeChat\Ocr;
use Kangcg\WeChat\Library\WeChat\OpenApi;
use Kangcg\WeChat\Library\WeChat\Qrcode;
use Kangcg\WeChat\Library\WeChat\Tag;
use Kangcg\WeChat\Library\WeChat\User;
use Kangcg\WeChat\Library\WeChatTrait;

/**
 * 微信公众号开发
 * $wechat = new WeChat(['appid' => '', 'appsecret' => '']);
 * Class WeChat
 * @property string $appid  微信 appid
 * @property string $appsecret  微信 appsecret
 * @property string $token  微信消息的token
 * @property string $accessToken  微信公众号的accessToken
 * @property string $encodingAESKey  微信的消息加密密匙
 * @property string $mch_id  微信支付商户ID
 * @property string $mch_key  微信支付商户KEY
 * @property string $sslCertPath  证书的相对路径 或者绝对路径
 * @property string $sslKeyPath; 证书的相对路径 或者绝对路径
 * @package Kang\Libs\WeChat
 */
class WeChat extends WeChatTrait
{
    use Comment;
    use Draft;
    use Media;
    use Menu;
    use MessageFK;
    use MessageMass;
    use MessageServer;
    use MessageTemplate;
    use Ocr;
    use OpenApi;
    use Qrcode;
    use Tag;
    use User;

    /**
     * 获取AccessToken
     * @return mixed
     */
    public function getAccessToken()
    {
        if (empty($this->_config['access_token'])) {
            $this->_config['access_token'] = $this->refreshAccessToken();
        }

        return $this->_config['access_token'];
    }

    /**
     * 刷新AccessToken
     * @return bool|mixed
     */
    public function refreshAccessToken()
    {
        $event = Event::create($this, self::EVENT_BEFORE_REFRESH_ACCESS_TOKEN);
        $this->trigger(self::EVENT_BEFORE_REFRESH_ACCESS_TOKEN, $event);
        if ($event->handled === true) {
            return $event->data['access_token'] ?? $event->data;
        }

        $url = Urls::ACCESS_TOKEN_URL;
        $url .= 'appid=' . $this->appid;
        $url .= '&secret=' . $this->appsecret;
        $url .= '&grant_type=client_credential';
        $result = $this->httpGet($url);
        if (!$result || !isset($result['access_token'])) {
            return false;
        }

        $event->data = $result;
        $this->trigger(self::EVENT_AFTER_REFRESH_ACCESS_TOKEN, $event);
        return $result['access_token'];
    }

    /**
     * @param $accessToken
     * @return $this
     */
    public function setAccessToken($accessToken)
    {
        $this->_config['access_token'] = $accessToken;
        return $this;
    }
}
